package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.EmailLoginBody;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.statistics.domain.RevenueStatistics;
import com.ruoyi.statistics.service.IStatisticsService;
import com.ruoyi.system.domain.bo.SysIpBo;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.domain.vo.SysIpVo;
import com.ruoyi.system.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * 登录验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;
    private final ISysConfigService configService;
    private final ISysIpService ipService;
    private final IStatisticsService statisticsService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        // 获取登录的ip
        HttpServletRequest request = ServletUtils.getRequest();
        final String ip = ServletUtils.getClientIP(request);
        // 拿到了ip
        //System.out.printf("打印一下登录的ip信息" + ip);
        String ipInfo = configService.selectConfigByKey(Constants.IP_INFO_RECORD);
        if (Objects.equals(ipInfo, "1")) {
            SysIpBo sysIpBo = new SysIpBo();
            sysIpBo.setStatus("0");
            sysIpBo.setIpaddr(ip);
            List<SysIpVo> sysIpVos = ipService.queryList(sysIpBo);
            if (CollectionUtils.isEmpty(sysIpVos)) {
                throw new ServiceException("请联系管理员授权IP：" + ip);
            }
        }
        Map<String, Object> ajax = new HashMap<>();
        ajax = loginService.loginInfo(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
        // 生成令牌
        //String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
        //    loginBody.getUuid());
        //ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 短信登录
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/smsLogin")
    public R<Map<String, Object>> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 邮件登录
     *
     * @param body 登录信息
     * @return 结果
     */
    @PostMapping("/emailLogin")
    public R<Map<String, Object>> emailLogin(@Validated @RequestBody EmailLoginBody body) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.emailLogin(body.getEmail(), body.getEmailCode());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 小程序登录(示例)
     *
     * @param xcxCode 小程序code
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/xcxLogin")
    public R<Map<String, Object>> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.xcxLogin(xcxCode);
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        RevenueStatistics revenueStatistics = statisticsService.selectUserRevenueTotalMonth();
        user.setLevel(StringUtils.isBlank(revenueStatistics.getGradeType())? "1": revenueStatistics.getGradeType());
        Map<String, Object> ajax = new HashMap<>();
        Set<String> rolePermission = loginUser.getRolePermission();
        if (!CollectionUtils.isEmpty(rolePermission)) {
            String disReturnControl = configService.selectConfigByKey("dis_return_control");
            if (!StringUtils.isBlank(disReturnControl)) {
                String[] split = disReturnControl.split(",");
                List<String> list = Arrays.asList(split);
                for (String roleKey : rolePermission) {
                    if (list.contains(roleKey)) {
                        // 为1 标识有权限可以查看
                        user.setDisReturnControl("1");
                        break;
                    }
                }
            }
        }
        ajax.put("user", user);
        ajax.put("roles", rolePermission);
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }
}
